<template>
    <div class="myLive">
        <div style="margin: 20px 0; font-size: 20px; color: #1E90FF">Face Registration</div>
        <div style="border: 1px solid #ccc; padding: 10px; border-radius: 10px; margin: 10px 0">
            <div style="color: #333; margin: 10px 0; font-size: 20px">User Information</div>
            <div style="color: #666; margin: 10px 0;">
                <span>Username: {{ user.username }}</span><br>
                <span>Name: {{ user.nickname }}</span><br>
            </div>
        </div>
        <div style="border: 1px solid #ccc; padding: 10px; border-radius: 10px; margin: 10px 0">
            <div style="color: #333; margin: 10px 0; font-size: 20px">Face Collection</div>
            <!--Video Display-->
            <video
                ref="video"
                width="250"
                height="188"
                autoplay
                class="mt20"
                style="background: #d9d9d9"
                v-show="!isCameraFlag"
            ></video>
            <!--Canvas Capture Stream-->
            <canvas ref="canvas" width="250" height="188" v-show="isCameraFlag" style="background-color: #eaeaea"></canvas>

            <br>

            <el-button type="danger" v-if="isCameraFlag" @click="callCamera">{{camera}}</el-button>
            <el-button type="primary" v-else @click="photograph">Take Photo</el-button>
            <el-button type="primary" v-if="commitFlag" @click="commit">Submit</el-button>
        </div>

    </div>
</template>



<script>
export default {
    name: "FaceRegister",
    data() {
        return {
            isCameraFlag: true,
            base64: "",
            acc: "",
            str1: "",
            isImg: false,
            commitFlag: false,
            camera: "Start Face Collection",
            user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
        };
    },

    mounted() {
    },

    methods: {
        // Call camera function
        callCamera() {
            this.isImg = true
            this.isCamera = true;
            console.log(this.isCamera);
            // H5 API call to access the computer's camera
            navigator.mediaDevices
                .getUserMedia({
                    audio: true, // Enable audio
                    video: true, // Enable video
                })
                .then((success) => {
                    var videoTracks = success.getVideoTracks();
                    this.$refs["video"].srcObject = success;
                    this.isCameraFlag = false;
                    // Real-time photo-taking effect
                    this.$refs["video"].play();
                    this.commitFlag = false
                })
                .catch((error) => {
                    console.error("Failed to open camera, please check if it is available!");
                    this.isCameraFlag = true;
                });
        },

        // Take a photo function
        photograph() {
            let ctx = this.$refs["canvas"].getContext("2d");
            ctx.drawImage(this.$refs["video"], 0, 0, 250, 188);
            let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
            let str = imgBase64.replace("data:image/jpeg;base64,", "");
            this.base64 = str;
            this.closeCamera()
            this.camera = "Recapture Face"
            this.commitFlag = true
        },

        // Close camera function
        closeCamera() {
            this.isImg=false
            if (!this.$refs["video"].srcObject) return;
            let stream = this.$refs["video"].srcObject;
            let tracks = stream.getTracks();
            tracks.forEach((track) => {
                track.stop();
            });
            this.$refs["video"].srcObject = null;
            this.isCameraFlag = true;
        },

        // Submit function for face recognition and registration
        commit() {
            // Get canvas object
            let canvas = this.$refs["canvas"]
            var formData = new FormData();
            var base64File = canvas.toDataURL("image/jpeg", 0.7);
            //var userName = $("#userName").val();
            formData.append("file", base64File);
            formData.append("name", this.user.username);
            formData.append("groupId", "101");
            $.ajax({
                type: "post",
                url: "http://localhost:8089/faceAdd",
                data: formData,
                contentType: false,
                processData: false,
                async: false,
                success: function (text) {
                    var res = JSON.stringify(text)
                    if (text.code == 0) {
                        alert("Registration successful")
                    } else {
                        alert(text.message)
                    }
                },
                error: function (error) {
                    alert(JSON.stringify(error))
                }
            });
        }
    },
};
</script>
